package zyc.web;

import zyc.pojo.User;
import zyc.service.UserService;
import zyc.service.impl.UserServiceImpl;
import zyc.utils.Webutils;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Random;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * @description:
 * @author: ZhaoYicong
 * @date: Created in 2020/7/19 9:01
 * @version: v1.0
 * @modified By:
 */

@WebServlet("/userServlet")
public class UserServlet extends BaseServlet {

    UserService userService = new UserServiceImpl();
//    String acode = null;
//    long first = 0; //获取验证码的第一次时间
//    long second = 0;//获取验证码的第二次时间
//    long third = 0;//获取邮箱验证码的第1次时间
//    long fourth=0;//获取邮箱验证码的第2次时间



    //

    protected void selecetjd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int id = Webutils.stringToint(req.getParameter("id"));
        List<User> jdusers = userService.getjds(id);

        req.setAttribute("jdusers",jdusers);

        req.getRequestDispatcher("pages/show/showjd.jsp").forward(req,resp);
    }

    //开启投票
    protected void start(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute("user");
        userService.endvote(user.getId(), 0);
        User newuser = userService.loginUser(user.getUsername(), user.getPassword());
        req.getSession().setAttribute("user", newuser);

        req.getRequestDispatcher("pages/user/login_success.jsp").forward(req, resp);
    }

    //结束投票
    protected void end(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute("user");
        userService.endvote(user.getId(), 1);
        User newuser = userService.loginUser(user.getUsername(), user.getPassword());
        req.getSession().setAttribute("user", newuser);

        req.getRequestDispatcher("pages/user/login_success.jsp").forward(req, resp);
    }


    //  发送邮件


    protected void sendms(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        if (req.getSession().getAttribute("first") != null) {

//            second = System.currentTimeMillis();
            req.getSession().setAttribute("second",System.currentTimeMillis());
        }
        //只搞一次
        if (req.getSession().getAttribute("first") == null) {
//            first = System.currentTimeMillis();
            req.getSession().setAttribute("first",System.currentTimeMillis());
        }
        long first=(Long)req.getSession().getAttribute("first");
        long second=0;
        if (req.getSession().getAttribute("second") != null){
            second=(Long) req.getSession().getAttribute("second");
        }

        if (second != 0 && second - first < 1000 * 100) {
            req.setAttribute("alert", "您的获取过于频繁请在" + (100 - ((second - first) / 1000)) + "秒后操作");
        } else {
            if (second != 0) {

                req.getSession().setAttribute("first",second);
                req.getSession().setAttribute("second",0);

//                first = second;
//                second = 0;
            }

            String toke = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);

            req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

            String code = req.getParameter("code");

            User user = (User) req.getSession().getAttribute("user");

            String email = user.getEmail();


            if (code != null && toke.equals(code)) {
                String acode=getcode();

                req.getSession().setAttribute("acode",acode);


                try {
                    email(acode, email);
                    req.setAttribute("alert", "验证码已发送，请注意查收");
                    req.getSession().setAttribute("third",System.currentTimeMillis());
//                    third=System.currentTimeMillis();
                } catch (Exception e) {
                    req.setAttribute("alert", "验证码发送失败");
                }


            } else {
                req.setAttribute("alert", "验证码错误");
            }
        }

        req.getRequestDispatcher("pages/upandcreat/updateuser.jsp").forward(req, resp);


    }

    //更改用户信息
    protected void updateUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        String code2 = req.getParameter("code2");

        long third=(Long)req.getSession().getAttribute("third");

        long fourth=System.currentTimeMillis();
        if (fourth-third>=1000*60*5){
            req.setAttribute("alert", "邮箱验证码已失效请重新获取");
            req.getSession().setAttribute("acode",null) ;
        } else if (code2 != null && req.getSession().getAttribute("acode") != null && req.getSession().getAttribute("acode").equals(code2)) {

            String password = req.getParameter("password");

            User user = (User) req.getSession().getAttribute("user");

            user.setPassword(password);
            userService.updateUser(user);
            req.setAttribute("alert", "密码修改成功");
            req.getSession().setAttribute("acode",null) ;

        } else {
            req.setAttribute("alert", "邮箱验证码错误");
        }

        req.getRequestDispatcher("pages/upandcreat/updateuser.jsp").forward(req, resp);


    }

    protected void vote(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //投票功能
        String targetid = req.getParameter("targetid");
        int tid = Webutils.stringToint(targetid);

        User user = (User) req.getSession().getAttribute("user");
        boolean vote = userService.vote(user.getId(), tid);
        if (vote) {
            userService.updatetotalvotes(tid);
        }
        User newuser = userService.getUserByid(user.getId());
        req.getSession().setAttribute("user", newuser);
        req.getRequestDispatcher("/userServlet?action=getUsers").forward(req, resp);
    }


    protected void canclevote(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //取消投票功能

        int targetid = Webutils.stringToint(req.getParameter("tragetid"));
        User user = (User) req.getSession().getAttribute("user");
        boolean vote = userService.canclevote(user.getId());
        if (vote) {
            userService.updatetotalvotes(targetid);
        }
        User newuser = userService.getUserByid(user.getId());
        req.getSession().setAttribute("user", newuser);
//        req.setAttribute("jdname",newuser.getJdname());
//        req.setAttribute("jdpassword",newuser.getJdpassword());
//
//        req.setAttribute("id",newuser.getId());
        req.getRequestDispatcher("/userServlet?action=getUsers").forward(req, resp);

    }

    protected void getUsers(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        //获取项目的功能
        User user = (User) req.getSession().getAttribute("user");


        if (user.getJdname()==null){
            req.setAttribute("alert","请先创建评委！");
            req.getRequestDispatcher("pages/user/login_success.jsp").forward(req,resp);
        }

        if (user.getTargetid() == 0 || user.getTargetid() == null) {

            List<User> users = userService.getUsers();
            req.setAttribute("users", users);
            req.setAttribute("head", "你还没有投票对象快来投票!");
            req.getRequestDispatcher("pages/show/showprojecet.jsp").forward(req, resp);
        } else {
            User userByid = userService.getUserByid(user.getTargetid());
            req.setAttribute("user", userByid);
            req.setAttribute("head", "你已经有了对象，祝他成功!");
            req.getRequestDispatcher("pages/show/showprojecet.jsp").forward(req, resp);
        }

    }


    protected void getUsersToindex(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取项目的功能



        List<User> users = userService.getUsers();

        req.setAttribute("users", users);
        req.getRequestDispatcher("index.jsp").forward(req, resp);

    }

    protected void loginjd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //评委登录功能
        String jdname = req.getParameter("jdname");
        String jdpassword = req.getParameter("jdpassword");
        String id = req.getParameter("id");
        int jid = Webutils.stringToint(id);
        User user = userService.loginJd(jdname, jdpassword, jid);
        if (user == null) {
            req.setAttribute("jmasg", "输入的信息有误");
            req.getRequestDispatcher("pages/user/login.jsp").forward(req, resp);
        } else {
            req.getSession().setAttribute("user", user);
            req.getRequestDispatcher("/userServlet?action=getUsers").forward(req, resp);
        }

    }

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //用户登录功能
        String username = req.getParameter("username");
        String password = req.getParameter("password");


        User user = userService.loginUser(username, password);

        if (user == null) {
            req.setAttribute("masg", "输入的信息有误");
            req.getRequestDispatcher("pages/user/login.jsp").forward(req, resp);
        } else {
            req.getSession().setAttribute("user", user);

            req.getRequestDispatcher("pages/user/login_success.jsp").forward(req, resp);
        }


    }


    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //退出功能
        req.getSession().invalidate();
        req.getRequestDispatcher("pages/user/login.jsp").forward(req, resp);
    }


    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //注册用户


        User user = Webutils.copyparamToBean(req.getParameterMap(), new User());
        if (userService.existsUser(user.getUsername())) {

            req.setAttribute("masg", "改用户名已经存在，请换一个用户名");
            req.getRequestDispatcher("pages/user/registuser.jsp").forward(req, resp);

        } else {
            userService.registUser(user);
            User user1 = userService.loginUser(user.getUsername(), user.getPassword());
            req.getSession().setAttribute("user", user1);
            req.getRequestDispatcher("pages/user/login_success.jsp").forward(req, resp);
        }

    }

    //创建评委
    protected void creatJd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String jdname = req.getParameter("jdname");
        String jdpassword = req.getParameter("jdpassword");
        int id = Webutils.stringToint(req.getParameter("id"));
        userService.registJd(id, jdname, jdpassword);
        req.getRequestDispatcher("userServlet?action=login").forward(req, resp);


    }

    //创建项目
    protected void creatPr(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String project = req.getParameter("project");
        int id = Webutils.stringToint(req.getParameter("id"));
        userService.registProjcet(project, id);
        req.getRequestDispatcher("userServlet?action=login").forward(req, resp);
    }


    //删除项目
    protected void deletePr(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int id = Webutils.stringToint(req.getParameter("id"));
        userService.registProjcet(null, id);
        userService.deletejdsbyid(id);
        userService.updatetotalvotes(id);
        User user = (User) req.getSession().getAttribute("user");
        //更新储存的user
        User user1 = userService.loginUser(user.getUsername(), user.getPassword());
        req.getSession().setAttribute("user", user1);
//        req.getRequestDispatcher("userServlet?action=login").forward(req,resp);


        req.getRequestDispatcher("pages/user/login_success.jsp").forward(req, resp);
    }

    //随机验证码函数
    public String getcode() {
        int a = (int) (Math.random() * (9999 - 1000) + 1000);
        String c = a + "";
        return c;
    }

    //发送邮件的方法
    public void email(String code, String email) throws Exception {
        Properties properties = new Properties();

        properties.put("mail.transport.protocol", "smtp");//连接协议

        properties.put("mail.smtp.host", "smtp.qq.com");//主机名

        properties.put("mail.smtp.port", 465);//端口号

        properties.put("mail.smtp.auth", "true");

        properties.put("mail.smtp.ssl.enable", "true");//设置是否使用ssl安全连接--使用

        properties.put("mail.debug", "true");//设置是否显示debug信息true会在控制台显示相关信息
        //得到回话对象
        Session session = Session.getInstance(properties);
        //获取邮件对象
        Message message = new MimeMessage(session);
        //设置发件人邮箱地址
        message.setFrom(new InternetAddress("1049566924@qq.com"));
        //设置收件人邮箱地址
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
        //设置邮件标题
        message.setSubject("验证码到了");
        //设置邮件内容
        message.setText("您的验证码是：" + code + "(请在五分钟内完成验证否则失效)");
        //得到邮差对象
        Transport transport = session.getTransport();
        //连接自己的邮箱账户
        transport.connect("1049566924@qq.com", "zxuvxjfybjoabdfi");//password为QQ邮箱开通smtp服务后得到的授权码

        //发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }
}
